package avicit.bdp.dgs.mdm.utils.api.request;

import avicit.platform6.core.exception.BusinessException;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

public abstract class RequestAdapter {

    private static final Logger LOG = LoggerFactory.getLogger(RequestAdapter.class);

    /**
     * 调用API接口
     * @param url
     * @return
     */
    public abstract String callApi(String applicationCode, String authCode, String logId, String data, String url);

    /**
     * 解析响应数据
     * @param result
     */
    public void parseResponseData(ResponseEntity<String> result){
        HttpStatus httpStatus = result.getStatusCode();
        int code = httpStatus.value();
        String body = result.getBody();
        LOG.info("调用接口返回状态码:{}", code);
        LOG.info("调用接口返回数据是:{}", body);
        if(code != HttpStatus.OK.value()){
            throw new BusinessException("调用API接口失败,状态码:" + code);
        }

        JSONObject jsonObject = JSONObject.parseObject(body);
        String retCode = jsonObject.getString("retCode");
        if(!"200".equals(retCode)){
            String msg = String.format("API接口返回状态失败,返回状态码:%s", retCode);
            LOG.error(msg);
            throw new BusinessException(msg);
        }
    }

}
